package com.example.pictureHandle;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.util.UUID;

import me.minetsh.imaging.IMGEditActivity;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_PICK_IMAGE = 100;
    private static final int REQUEST_CODE_EDIT_IMAGE = 101;
    private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 200;

    private TextView textView;
    private static final String TAG = "MainActivity";

    // 保存编辑图片的路径
    private String editedImagePath;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        Log.d(TAG, "onCreate: 初始化界面");
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE);
        }

        textView = findViewById(R.id.edit_picture);
        textView.setOnClickListener(v -> {
            Log.d(TAG, "点击按钮：准备打开图片选择器");
            openImagePicker();
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "存储权限已授权", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "存储权限被拒绝，无法保存编辑图片到公共目录", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void openImagePicker() {
        Log.d(TAG, "打开系统图片选择器");
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d(TAG, "onActivityResult: requestCode = " + requestCode + ", resultCode = " + resultCode);

        if (resultCode != RESULT_OK) {
            Log.w(TAG, "结果无效或用户取消了操作");
            return;
        }

        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            Uri sourceUri = data.getData();
            Log.d(TAG, "用户选择的图片 URI: " + sourceUri);

            if (sourceUri != null) {
                if ("content".equals(sourceUri.getScheme())) {
                    Uri fileUri = getFileUriFromContentUri(sourceUri);
                    if (fileUri != null) {
                        sourceUri = fileUri;
                        Log.d(TAG, "转换后的文件 URI: " + sourceUri);
                    } else {
                        Log.w(TAG, "转换 content:// URI 失败，仍用原 URI");
                    }
                }

                File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                if (!picturesDir.exists()) {
                    picturesDir.mkdirs();
                }
                File outputFile = new File(picturesDir, "edited_" + UUID.randomUUID().toString() + ".jpg");
                editedImagePath = outputFile.getAbsolutePath();

                Log.d(TAG, "编辑图片保存路径: " + editedImagePath);

                Intent intent = new Intent(MainActivity.this, IMGEditActivity.class);
                intent.putExtra(IMGEditActivity.EXTRA_IMAGE_URI, sourceUri);
                intent.putExtra(IMGEditActivity.EXTRA_IMAGE_SAVE_PATH, editedImagePath);

                Log.d(TAG, "准备跳转到 IMGEditActivity");
                try {
                    startActivityForResult(intent, REQUEST_CODE_EDIT_IMAGE);
                    Log.d(TAG, "跳转成功");
                } catch (Exception e) {
                    Log.e(TAG, "跳转到 IMGEditActivity 失败: " + e.getMessage(), e);
                    Toast.makeText(this, "跳转失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            } else {
                Log.w(TAG, "sourceUri 为空，无法跳转");
                Toast.makeText(this, "未获取到图片 URI", Toast.LENGTH_SHORT).show();
            }
        }
        else if (requestCode == REQUEST_CODE_EDIT_IMAGE) {
            Log.d(TAG, "返回自 IMGEditActivity");

            // 如果返回 data 中没有 URI，就使用我们保存的路径
            Uri resultUri = null;

            if (data != null && data.getData() != null) {
                resultUri = data.getData();
                Log.d(TAG, "从返回的 Intent 中获取到 URI: " + resultUri);
            } else if (editedImagePath != null) {
                File file = new File(editedImagePath);
                if (file.exists()) {
                    resultUri = Uri.fromFile(file);
                    Log.d(TAG, "使用之前保存的路径构造 URI: " + resultUri);
                } else {
                    Log.w(TAG, "保存路径文件不存在: " + editedImagePath);
                }
            }

            if (resultUri != null) {
                Toast.makeText(this, "图片编辑完成，保存路径: " + resultUri.getPath(), Toast.LENGTH_SHORT).show();
                Log.d(TAG, "图片保存路径: " + resultUri.getPath());
            } else {
                Log.w(TAG, "未获取到编辑后的图片 URI");
                Toast.makeText(this, "图片编辑失败或未保存", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private Uri getFileUriFromContentUri(Uri contentUri) {
        // 使用 ContentResolver 查询真实文件路径（适合 media 存储）
        String[] projection = { "_data" };
        try (Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow("_data");
                String filePath = cursor.getString(columnIndex);
                if (!TextUtils.isEmpty(filePath)) {
                    return Uri.fromFile(new File(filePath));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}